package server

import (
	"fmt"
	"server/base"
	"server/common/dao/group"
	group2 "server/common/models/group"
	pool2 "server/common/models/pool"
	"server/pkg/cron/constant"
	"server/pkg/log"
	"time"
)

type PostPool struct {
	constant.CornRegisterServiceParamBase
}

func (p *PostPool) GetCorn() string {
	// 每周5晚上8点
	return "0 20 * * 5"
}

func (p *PostPool) Run() {
	fmt.Println("PostPool", "开始匹配中")

	// 完成以前的匹配
	_ = p.doneMatch()

	// 获取所有报名的用户
	var poolMenUserRegister []pool2.PoolUserRegister
	var poolWomenUserRegister []pool2.PoolUserRegister
	base.Mysql.Find(&poolMenUserRegister, "status = ? and user_gender = 1", "wait")
	base.Mysql.Find(&poolWomenUserRegister, "status = ?  and user_gender = 2", "wait")

	errCnt := 0
	for true {
		if int64(len(poolMenUserRegister)) < base.App.Config.App.PoolMatch.Min || int64(len(poolWomenUserRegister)) < base.App.Config.App.PoolMatch.Min {
			break
		}

		// 创建群组
		Group, err := group.GroupDao.CreateGroup("CP大本营")
		if err != nil {
			if errCnt > 3 {
				break
			}
			errCnt++
			log.Error("创建群组失败", err, Group)
			continue
		}

		for i := 0; i < int(base.App.Config.App.PoolMatch.Max); i++ {
			if len(poolMenUserRegister) == 0 || len(poolWomenUserRegister) == 0 {
				break
			}
			_ = p.matchPool(poolMenUserRegister[0].UserId, Group.Id)
			_ = p.matchPool(poolWomenUserRegister[0].UserId, Group.Id)
			poolMenUserRegister = append(poolMenUserRegister[:0], poolMenUserRegister[1:]...)
			poolWomenUserRegister = append(poolWomenUserRegister[:0], poolWomenUserRegister[1:]...)

		}
	}

	// 剩下的标记为失败
	for _, item := range poolMenUserRegister {
		_ = base.Mysql.Model(&pool2.PoolUserRegister{}).Where("user_id = ?", item.UserId).
			Update(map[string]interface{}{"status": "fail", "update_time": time.Now().Unix()}).Error
	}

	for _, item := range poolWomenUserRegister {
		_ = base.Mysql.Model(&pool2.PoolUserRegister{}).Where("user_id = ?", item.UserId).
			Update(map[string]interface{}{"status": "fail", "update_time": time.Now().Unix()}).Error
	}

	fmt.Println("PostPool", "匹配成功")
}

// 完成以前的匹配
func (p *PostPool) doneMatch() error {
	// 修改状态
	err := base.Mysql.Model(&group2.Group{}).Where("status = ?", "doing").
		Update(map[string]interface{}{"status": "done", "update_time": time.Now().Unix()}).Error
	if err != nil {
		log.Error("[doneMatch]修改匹配状态失败", err, nil)
		return err
	}

	err = base.Mysql.Model(pool2.PoolUserRegister{}).Where("status = ? or status = ?", "match", "doing").
		Update(map[string]interface{}{"status": "done", "update_time": time.Now().Unix()}).Error
	if err != nil {
		log.Error("[doneMatch] 修改匹配状态失败", err, nil)
		return err
	}

	err = base.Mysql.Model(&group2.GroupUser{}).Where("status = ?", "doing").
		Update(map[string]interface{}{"status": "done", "update_time": time.Now().Unix()}).Error
	if err != nil {
		log.Error("[doneMatch] 修改匹配状态失败", err, nil)
		return err
	}
	return nil
}

func (p *PostPool) matchPool(userId int64, groupId int64) error {
	// 修改状态
	err := base.Mysql.Model(&pool2.PoolUserRegister{}).Where("user_id = ? and status = ?", userId, "wait").
		Update(map[string]interface{}{"status": "doing", "match_group_id": groupId, "update_time": time.Now().Unix()}).Error
	if err != nil {
		log.Error("修改匹配状态失败", err, []interface{}{userId, groupId})
		return err
	}

	// 加入群组
	err = group.GroupDao.JoinGroup(userId, groupId)
	if err != nil {
		log.Error("加入群组失败", err, []interface{}{userId, groupId})
		return err
	}
	return nil
}
